/**
 * XMLMod
 * This utility is designed to allow modification of an xml file 
 * via an Ant call.  See the documentation for usage examples
 */
package com.xmlmod.tasks;

import java.util.Vector;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.xmlmod.util.XMLModResource;
import com.xmlmod.util.XTrace;

/**
 * @author W. Cowger
 *
 */
public class Remove {
	private String path;
	private int logLevel;
	private XMLModResource resource;
	
	public Remove(){
		resource = XMLModResource.getResource("com.xmlmod.util.resource.RemoveResource");
	}
	
	/**
	 * Sets the path attribute
	 * 
	 * @param path -Path of element to remove
	 */
	public void setPath(String path){
		this.path = path;
	}
	
	/**
	 * Takes all nodes matching the XTRace given and removes them from the document
	 *  
	 * @param task- The parent task of this process
	 */
	public void process(XMLMod task){
		logLevel = ((XMLMod)task).getLogLevel();
		task.log(resource.getMessage("REMOVE_PATH", path), logLevel);
		
		// Get the most current version of the document
		Document doc = task.loadDocument();
		
		// Get a list of all node matching the given XTrace notation
		Vector<Node> matches = XTrace.tracePath(doc, path, task);
		boolean modified = false;
		
		// For each matching node, remove it from its parent
		for(int i=0; i<matches.size(); i++){
			Node match = matches.get(i);
			task.log(resource.getMessage("REMOVE_NODE_MATCH", match.getNodeName()), logLevel);
			match.getParentNode().removeChild(match); //doc.removeChild(match);
			modified = true;
		}
		
		// If a change was made send the modified document back to the calling task
		if(modified){
			task.log(resource.getMessage("REMOVE_DOC_UPDATED"), logLevel);
			task.setDocument(doc);
		// If no change was made inform the user
		}else{
			task.log(resource.getMessage("REMOVE_NO_CHANGES", path));
		}
	}
}
